package com.zenith.middleware.service.impl;

import com.zenith.common.result.Result;
import com.zenith.common.result.PageResult;
import com.zenith.common.constant.RedisKeyConstant;
import com.zenith.common.constant.RedisTtlConstant;
import com.zenith.middleware.feign.article.ArticleServiceFeignClient;
import com.zenith.middleware.po.dto.article.*;
import com.zenith.middleware.po.vo.article.*;
import com.zenith.middleware.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

/**
 * 文章服务实现类
 */
@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {
    
    private final ArticleServiceFeignClient articleServiceFeignClient;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    public ArticleServiceImpl(ArticleServiceFeignClient articleServiceFeignClient) {
        this.articleServiceFeignClient = articleServiceFeignClient;
    }
    
    // =========================== 文章管理相关接口 ===========================
    
    /**
     * 分页查询文章
     */
    @Override
    public Result<PageResult<ArtArticleVO>> getArtArticlePage(ArtArticleDTO query) {
        // 构建缓存键
        String cacheKey = RedisKeyConstant.ARTICLE_PAGE + (query.getPageNum() != null ? query.getPageNum() : 1) + "_" + 
                         (query.getPageSize() != null ? query.getPageSize() : 10);
        
        // 尝试从缓存获取
        Result<PageResult<ArtArticleVO>> cachedResult = (Result<PageResult<ArtArticleVO>>) redisTemplate.opsForValue().get(cacheKey);
        if (cachedResult != null) {
            log.info("从缓存获取文章分页数据: key={}", cacheKey);
            return cachedResult;
        }
        
        // 调用Feign客户端获取数据
        Result<PageResult<ArtArticleVO>> result = articleServiceFeignClient.getArtArticlePage(query);
        
        // 缓存结果
        if (result != null && result.getData() != null) {
            redisTemplate.opsForValue().set(cacheKey, result, RedisTtlConstant.ARTICLE_PAGE_TTL, TimeUnit.SECONDS);
            log.info("缓存文章分页数据: key={}", cacheKey);
        }
        
        return result;
    }
    
    /**
     * 创建文章
     */
    @Override
    public Result<Boolean> createArtArticle(ArtArticleDTO articleDTO) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.createArtArticle(articleDTO);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearArticleCache();
        }
        
        return result;
    }

    /**
     * 更新文章
     */
    @Override
    public Result<Boolean> updateArtArticle(ArtArticleDTO articleDTO) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.updateArtArticle(articleDTO);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearArticleCache();
        }
        
        return result;
    }

    /**
     * 删除文章
     */
    @Override
    public Result<Boolean> deleteArtArticle(Long id) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.deleteArtArticle(id);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearArticleCache();
        }
        
        return result;
    }

    /**
     * 发布文章
     */
    @Override
    public Result<Boolean> publishArtArticle(Long id) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.publishArtArticle(id);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearArticleCache();
        }
        
        return result;
    }

    /**
     * 获取文章详情
     */
    @Override
    public Result<ArtArticleDTO> getArtArticleDetail(Long id) {
        // 构建缓存键
        String cacheKey = RedisKeyConstant.ARTICLE_DETAIL + id;
        
        // 尝试从缓存获取
        Result<ArtArticleDTO> cachedResult = (Result<ArtArticleDTO>) redisTemplate.opsForValue().get(cacheKey);
        if (cachedResult != null) {
            log.info("从缓存获取文章详情数据: key={}", cacheKey);
            return cachedResult;
        }
        
        // 调用Feign客户端获取数据
        Result<ArtArticleDTO> result = articleServiceFeignClient.getArtArticleDetail(id);
        
        // 缓存结果
        if (result != null && result.getData() != null) {
            redisTemplate.opsForValue().set(cacheKey, result, RedisTtlConstant.ARTICLE_INFO_TTL, TimeUnit.SECONDS);
            log.info("缓存文章详情数据: key={}", cacheKey);
        }
        
        return result;
    }

    // =========================== 文章分类相关接口 ===========================

    /**
     * 分页查询文章分类
     */
    @Override
    public Result<PageResult<ArtCategoryVO>> getArtCategoryPage(ArtCategoryDTO query) {
        // 构建缓存键
        String cacheKey = RedisKeyConstant.CATEGORY_PAGE + (query.getPageNum() != null ? query.getPageNum() : 1) + "_" + 
                         (query.getPageSize() != null ? query.getPageSize() : 10);
        
        // 尝试从缓存获取
        Result<PageResult<ArtCategoryVO>> cachedResult = (Result<PageResult<ArtCategoryVO>>) redisTemplate.opsForValue().get(cacheKey);
        if (cachedResult != null) {
            log.info("从缓存获取文章分类分页数据: key={}", cacheKey);
            return cachedResult;
        }
        
        // 调用Feign客户端获取数据
        Result<PageResult<ArtCategoryVO>> result = articleServiceFeignClient.getArtCategoryPage(query);
        
        // 缓存结果
        if (result != null && result.getData() != null) {
            redisTemplate.opsForValue().set(cacheKey, result, RedisTtlConstant.ARTICLE_PAGE_TTL, TimeUnit.SECONDS);
            log.info("缓存文章分类分页数据: key={}", cacheKey);
        }
        
        return result;
    }

    /**
     * 获取分类树结构
     */
    @Override
    public Result<ArtCategoryVO> getArtCategoryTree() {
        // 构建缓存键
        String cacheKey = RedisKeyConstant.CATEGORY_TREE;
        
        // 尝试从缓存获取
        Result<ArtCategoryVO> cachedResult = (Result<ArtCategoryVO>) redisTemplate.opsForValue().get(cacheKey);
        if (cachedResult != null) {
            log.info("从缓存获取文章分类树数据: key={}", cacheKey);
            return cachedResult;
        }
        
        // 调用Feign客户端获取数据
        Result<ArtCategoryVO> result = articleServiceFeignClient.getArtCategoryTree();
        
        // 缓存结果
        if (result != null && result.getData() != null) {
            redisTemplate.opsForValue().set(cacheKey, result, RedisTtlConstant.ARTICLE_INFO_TTL, TimeUnit.SECONDS);
            log.info("缓存文章分类树数据: key={}", cacheKey);
        }
        
        return result;
    }

    /**
     * 创建文章分类
     */
    @Override
    public Result<Boolean> createArtCategory(ArtCategoryDTO categoryDTO) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.createArtCategory(categoryDTO);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearCategoryCache();
        }
        
        return result;
    }

    /**
     * 更新文章分类
     */
    @Override
    public Result<Boolean> updateArtCategory(ArtCategoryDTO categoryDTO) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.updateArtCategory(categoryDTO);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearCategoryCache();
        }
        
        return result;
    }

    /**
     * 删除文章分类
     */
    @Override
    public Result<Boolean> deleteArtCategory(Long id) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.deleteArtCategory(id);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearCategoryCache();
        }
        
        return result;
    }

    // =========================== 文章评论相关接口 ===========================

    /**
     * 创建文章评论
     */
    @Override
    public Result<Boolean> createArtComment(ArtCommentDTO comment) {
        // 将DTO转换为VO
        ArtCommentVO commentVO = new ArtCommentVO();
        BeanUtils.copyProperties(comment, commentVO);
        return articleServiceFeignClient.createArtComment(commentVO);
    }

    /**
     * 删除文章评论
     */
    @Override
    public Result<Boolean> deleteArtComment(Long id) {
        return articleServiceFeignClient.deleteArtComment(id);
    }

    // =========================== 文章互动相关接口 ===========================

    /**
     * 创建文章互动（点赞、收藏、分享等）
     */
    @Override
    public Result<Boolean> createArtInteraction(ArtInteractionDTO interaction) {
        // 将DTO转换为VO
        ArtInteractionVO interactionVO = new ArtInteractionVO();
        BeanUtils.copyProperties(interaction, interactionVO);
        return articleServiceFeignClient.createArtInteraction(interactionVO);
    }

    /**
     * 删除文章互动
     */
    @Override
    public Result<Boolean> deleteArtInteraction(Long id) {
        return articleServiceFeignClient.deleteArtInteraction(id);
    }

    // =========================== 文章标签相关接口 ===========================

    /**
     * 分页查询文章标签
     */
    @Override
    public Result<PageResult<ArtTagVO>> getArtTagPage(ArtTagDTO query) {
        // 构建缓存键
        String cacheKey = RedisKeyConstant.TAG_PAGE + (query.getPageNum() != null ? query.getPageNum() : 1) + "_" + 
                         (query.getPageSize() != null ? query.getPageSize() : 10);
        
        // 尝试从缓存获取
        Result<PageResult<ArtTagVO>> cachedResult = (Result<PageResult<ArtTagVO>>) redisTemplate.opsForValue().get(cacheKey);
        if (cachedResult != null) {
            log.info("从缓存获取文章标签分页数据: key={}", cacheKey);
            return cachedResult;
        }
        
        // 调用Feign客户端获取数据
        Result<PageResult<ArtTagVO>> result = articleServiceFeignClient.getArtTagPage(query);
        
        // 缓存结果
        if (result != null && result.getData() != null) {
            redisTemplate.opsForValue().set(cacheKey, result, RedisTtlConstant.ARTICLE_PAGE_TTL, TimeUnit.SECONDS);
            log.info("缓存文章标签分页数据: key={}", cacheKey);
        }
        
        return result;
    }

    /**
     * 创建文章标签
     */
    @Override
    public Result<Boolean> createArtTag(ArtTagDTO tagDTO) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.createArtTag(tagDTO);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearTagCache();
        }
        
        return result;
    }

    /**
     * 更新文章标签
     */
    @Override
    public Result<Boolean> updateArtTag(ArtTagDTO tagDTO) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.updateArtTag(tagDTO);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearTagCache();
        }
        
        return result;
    }

    /**
     * 删除文章标签
     */
    @Override
    public Result<Boolean> deleteArtTag(Long id) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.deleteArtTag(id);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearTagCache();
        }
        
        return result;
    }

    // =========================== 文章专题相关接口 ===========================

    /**
     * 分页查询文章专题
     */
    @Override
    public Result<PageResult<ArtTopicVO>> getArtTopicPage(ArtTopicDTO query) {
        // 构建缓存键
        String cacheKey = RedisKeyConstant.TOPIC_PAGE + (query.getPageNum() != null ? query.getPageNum() : 1) + "_" + 
                         (query.getPageSize() != null ? query.getPageSize() : 10);
        
        // 尝试从缓存获取
        Result<PageResult<ArtTopicVO>> cachedResult = (Result<PageResult<ArtTopicVO>>) redisTemplate.opsForValue().get(cacheKey);
        if (cachedResult != null) {
            log.info("从缓存获取文章专题分页数据: key={}", cacheKey);
            return cachedResult;
        }
        
        // 调用Feign客户端获取数据
        Result<PageResult<ArtTopicVO>> result = articleServiceFeignClient.getArtTopicPage(query);
        
        // 缓存结果
        if (result != null && result.getData() != null) {
            redisTemplate.opsForValue().set(cacheKey, result, RedisTtlConstant.ARTICLE_PAGE_TTL, TimeUnit.SECONDS);
            log.info("缓存文章专题分页数据: key={}", cacheKey);
        }
        
        return result;
    }

    /**
     * 创建文章专题
     */
    @Override
    public Result<Boolean> createArtTopic(ArtTopicDTO topicDTO) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.createArtTopic(topicDTO);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearTopicCache();
        }
        
        return result;
    }

    /**
     * 更新文章专题
     */
    @Override
    public Result<Boolean> updateArtTopic(ArtTopicDTO topicDTO) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.updateArtTopic(topicDTO);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearTopicCache();
        }
        
        return result;
    }

    /**
     * 删除文章专题
     */
    @Override
    public Result<Boolean> deleteArtTopic(Long id) {
        // 调用Feign客户端
        Result<Boolean> result = articleServiceFeignClient.deleteArtTopic(id);
        
        // 清除相关缓存
        if (result != null && result.getData() != null && result.getData()) {
            clearTopicCache();
        }
        
        return result;
    }
    
    // =========================== 缓存清理方法 ===========================
    
    /**
     * 清除文章相关缓存
     */
    private void clearArticleCache() {
        redisTemplate.delete(RedisKeyConstant.ARTICLE_PAGE + "*");
        redisTemplate.delete(RedisKeyConstant.ARTICLE_DETAIL + "*");
        log.info("清除文章相关缓存");
    }
    
    /**
     * 清除分类相关缓存
     */
    private void clearCategoryCache() {
        redisTemplate.delete(RedisKeyConstant.CATEGORY_PAGE + "*");
        redisTemplate.delete(RedisKeyConstant.CATEGORY_TREE);
        log.info("清除分类相关缓存");
    }
    
    /**
     * 清除标签相关缓存
     */
    private void clearTagCache() {
        redisTemplate.delete(RedisKeyConstant.TAG_PAGE + "*");
        log.info("清除标签相关缓存");
    }
    
    /**
     * 清除专题相关缓存
     */
    private void clearTopicCache() {
        redisTemplate.delete(RedisKeyConstant.TOPIC_PAGE + "*");
        log.info("清除专题相关缓存");
    }
}